package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.client.OrderClients;
import com.qf.pojo.entity.QfOrder;
import com.qf.pojo.repVo.BaseResp;
import com.qf.service.PayService;
import com.qf.utils.AlipayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    OrderClients orderClients;

    @Autowired
    AlipayUtils alipayUtils;
    @Autowired
    RabbitTemplate rabbitTemplate;
    private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Override
    public BaseResp pay(Map map) {
        logger.debug("进入了支付流程：{}"+map);
        String orderid = map.get("orderid").toString();
        //远程调用order服务
        BaseResp byOrderid = orderClients.findByOrderid(orderid);
        if (byOrderid.getCode()==0){
            return byOrderid;
        }
        //从baseresp中解析出 订单信息
        Object data = byOrderid.getData();
        String s = JSONObject.toJSONString(data);
        QfOrder qfOrder = JSONObject.parseObject(s, QfOrder.class);
        //支付流程
        String pay = alipayUtils.pay(orderid, qfOrder.getOrderPay());
        logger.debug("获取到了支付宝的提交form表单：{}"+pay);
        //远程调用order服务，将支付状态更改为 正在支付的状态
        BaseResp baseResp = orderClients.updateOrderStatus(orderid,3);
        if (baseResp.getCode()==0){
            return new BaseResp(0,"支付失败！",null,null);
        }
        //发送一条延迟消息，设置5分钟的时间，如果5分钟用户未付款，则直接将支付状态修改为 取消支付
        rabbitTemplate.convertAndSend("pay-dead-exchange", "deadpay", orderid, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置当前过期的时间,如果30秒，用户未支付，则直接将该笔交易置为取消支付
                message.getMessageProperties().setExpiration("30000");
                return message;
            }
        });
        return new BaseResp(1,"支付调用成功！",pay,null);
    }

    @Override
    public void notifyResult(HttpServletRequest request) {
        logger.debug("进入了支付宝的回调接口");
        Map map = alipayUtils.notifyUrl(request);
        logger.debug("支付宝回调的参数为：{}"+map);
        //1.验签是否成功
        if ((Boolean) map.get("signVerified")){
            logger.debug("支付宝验签成功！继续流程{}");
            //如果验签成功，则进入下方逻辑
            Map payResult =(Map) map.get("payResult");
            Double total_amount = Double.valueOf(payResult.get("total_amount").toString());
            String out_trade_no = payResult.get("out_trade_no").toString();
            String trade_status = payResult.get("trade_status").toString();
            if (trade_status.equals("TRADE_SUCCESS")){
                logger.debug("支付宝返回状态为 支付成功！继续流程{}");

                //如果支付宝返回的交易状态为 TRADE_SUCCESS 则代表用户已经进行了支付
                //通过订单号获取到该笔订单信息，比对用户支付的金额是否与数据库保持一致
                BaseResp byOrderid = orderClients.findByOrderid(out_trade_no);
                Object data = byOrderid.getData();
                String s = JSONObject.toJSONString(data);
                QfOrder qfOrder = JSONObject.parseObject(s, QfOrder.class);
                //继续进行支付的 价格比对
                if (total_amount.compareTo(qfOrder.getOrderPay())==0){
                    //说明用户支付的金额与数据库保持一致，支付结束，将order表中的支付状态更改为已支付
                    BaseResp baseResp = orderClients.updateOrderStatus(out_trade_no,2);
                    if (baseResp.getCode()==1){
                        logger.debug("订单状态修改为 已支付！");
                    }
                }
            }
        }else {
            logger.error("验签失败！");
        }
    }
}
